package com.qdy.pay.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qdy.pay.common.*;
import com.qdy.pay.mode.WeiXinOrderResData;
import com.qdy.pay.mode.WeiXinPayClientResData;
import com.qdy.pay.mode.WeiXinPayData;
import com.thoughtworks.xstream.XStream;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class WeiXinAppPayService extends BaseService{
    private Log log=new Log(LoggerFactory.getLogger(WeiXinAppPayService.class));
    public WeiXinAppPayService() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        super(WeixinConfigure.APP_PAY_API);
    }

    /**
     * 请求微信小程序统一下单服务
     * 返回小程序提效订单所需要的数据
     * @param weiXinPayData 这个数据对象里面包含了API要求提交的各种数据字段
     * @return API返回的数据
     * @throws Exception
     */
    public Map<String ,Object> request(WeiXinPayData weiXinPayData) throws Exception {
        try{
            //--------------------------------------------------------------------
            //发送HTTPS的Post请求到API地址
            //--------------------------------------------------------------------
            log.i("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
            weiXinPayData.setSign(Signature.getSign(weiXinPayData.toMap()));
            String responseString = sendPost(weiXinPayData);
            log.i("LLLLLLL"+responseString);
            Object ob=Util.getObjectFromXML(responseString,WeiXinOrderResData.class);
            log.i(ob.toString());
            WeiXinOrderResData weiXinOrderResData= JSONObject.toJavaObject((JSON) JSON.toJSON(ob),WeiXinOrderResData.class);
            long time = System.currentTimeMillis()/1000;
            Map<String,Object> signMap=new HashMap<>();
            signMap.put("appId",WeixinConfigure.getAppID());
            signMap.put("nonceStr",RandomStringGenerator.getRandomStringByLength(32));
            signMap.put("package","prepay_id="+weiXinOrderResData.getPrepay_id());
            signMap.put("signType","MD5");
            signMap.put("timeStamp",time+"");
            signMap.put("paySign",Signature.getSign(signMap));
            Map<String,Object> dataMap=new HashMap<>();
            dataMap.put("sign",signMap);
            dataMap.put("payId",weiXinOrderResData.getPrepay_id());
            return dataMap;
        }catch (Exception e){
            log.e(e.getMessage());
            return null;
        }

    }
}
